<?php

namespace App\Common\Comp\Examine;

use App\Common\Utill\Utill;
use App\Service\CheckContentLogService;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

/**
 * [数美审核类]
 * 机审登录网址： https://console.ishumei.com
 * 人审登录网址： https://next-audit.ishumei.com/censor/login
 * 账号:854600347@qq.com  密码:RVPYOQKT
 * 产品文档地址：https://console.ishumei.com/new/document
 */
class ShuMei extends Substrate
{

    protected static $url       = '';//回调域名地址
    protected static $appId     = '';//应用ID
    protected static $accessKey = '';//应用秘钥
    protected static $config    = [];//配置
    protected static $headers   = ["Content-Type'=>'application/json; charset=utf-8"];//请求头

    /**
     * ShuMei constructor.
     */
    public function __construct()
    {
        $config = Config::get('ExamineConfig.ShuMei');
        static::$url            = Config::get('ExamineConfig.url');
        static::$appId          = $config['appId'];
        static::$accessKey      = $config['accessKey'];
        static::$config         = $config;
    }


    /**
     * 文本文字检测
     * @param $dataId
     * @param $userId
     * @param $content
     * @param $sceneId
     * @return array
     */
    public static function textCheck($dataId,$userId,$content,$sceneId,$extraData=[])
    {
        //请求内容
        $strategy = static::$config['textCheck']['eventId'][$sceneId];
        $data = [
            'accessKey' => static::$accessKey,          //应用秘钥
            'appId'     => static::$appId,              //应用ID
            'eventId'   => $strategy,                    //事件标识
            'type'      => 'DEFAULT',                   //检测的风险类型
            'data'      => ['text' => $content,'tokenId' => $dataId]
        ];

        // 发送请求
        $res = Utill::httpRequest(static::$config['textCheck']['checkUrl'], 'POST', json_encode($data), static::$headers, false);
        $res = json_decode($res,true);

        (new CheckContentLogService())->AddCheckContenLog(2,$sceneId,1,$res['requestId'],$userId,$dataId,json_encode($data,JSON_UNESCAPED_UNICODE),json_encode($res,JSON_UNESCAPED_UNICODE));

        if($res['code'] == 1100){ //code 1100：成功 1901：QPS 超限1902：参数不合法 1903：服务失败 9100：余额不足 9101：无权限操作
            if ($res['riskLevel'] == 'REJECT' || $res['riskLevel'] == 'REVIEW') { // PASS=>正常 REVIEW=>可疑  REJECT=>违规
                $result = ['code' => 91002,'message' => '存在不合规内容 请调整'];
            }

            if ($res['riskLevel'] == 'PASS') { // 建议动作，2：建议删除，1：建议审核，0：建议通过
                $result = ['code' => 200,'message' => '数据一切正常'];
            }
        }else{
            //接口请求失败
            $result = ['code' => 200,'message' => '数据检测请求异常'];
        }
        return $result;
    }

    /**
     * 文本文字检测
     * @param $dataId
     * @param $userId
     * @param $content
     * @param $sceneId
     * @return array
     */
    public static function textBatchCheck($dataId,$userId,$content,$sceneId)
    {
        $info = [];
        $result = [];
        foreach ($content as $key => $value){
            //请求内容
            $strategy = static::$config['textCheck']['eventId'][$sceneId];
            $data = [
                'accessKey' => static::$accessKey,          //应用秘钥
                'appId'     => static::$appId,              //应用ID
                'eventId'   => $strategy,                   //事件标识
                'type'      => 'DEFAULT',                   //检测的风险类型
                'data'      => ['text' => $value,'tokenId' => $dataId]
            ];
            // 发送请求
            $res = Utill::httpRequest(static::$config['textCheck']['checkUrl'], 'POST', json_encode($data), static::$headers, false);
            $res = json_decode($res,true);

            (new CheckContentLogService())->AddCheckContenLog(2,$sceneId,1,$res['requestId'],$userId,$dataId,json_encode($data,JSON_UNESCAPED_UNICODE),json_encode($res,JSON_UNESCAPED_UNICODE));

            if($res['code'] == 1100){ //code 1100：成功 1901：QPS 超限1902：参数不合法 1903：服务失败 9100：余额不足 9101：无权限操作
                if ($res['riskLevel'] == 'REJECT' || $res['riskLevel'] == 'REVIEW') { // PASS=>正常 REVIEW=>可疑  REJECT=>违规
//                    $info[$key] = ['code' => 91002,'message' => '违规数据'];
                    $info = ['code' => 91002,'message' => '存在不合规内容 请调整'];
                    $result = $info;
                }
                if ($res['riskLevel'] == 'PASS') { // 建议动作，2：建议删除，1：建议审核，0：建议通过
//                    $info[$key] = ['code' => 200,'message' => '数据一切正常'];
                    $info = ['code' => 200,'message' => '数据一切正常'];
                }
            }else{
                //接口请求失败
//                $info[$key] = ['code' => 91001,'message' => '数据检测请求异常'];
                $info = ['code' => 200,'message' => '数据检测请求异常'];
                return $info;
            }
        }

        $info = !empty($result) ? $result : $info;
        return $info;
    }

    /**
     * 图片检测
     * @param $dataId
     * @param $userId
     * @param $content
     * @param $sceneId
     * @return array
     */
    public static function imgCheck($dataId,$userId,$content,$sceneId,$extraData=[])
    {
        $info = [];
        if(empty($content)){
            return $info;
        }

        $img = [];
        foreach ($content as $key => $value){
            $img[] = [
                'btid' => (string)$key,
                'img' => $value,
            ];
        }
        $strategy = static::$config['imgCheck']['eventId'][$sceneId];
        $data = [
            'accessKey' => static::$accessKey,    //应用秘钥
            'appId'     => static::$appId,        //应用ID
            'eventId'   => $strategy[0],          //事件标识
            'type'      => $strategy[1],          //检测的风险类型
            'tokenId'   => $dataId,               //用户账号标识， 建议使用贵司用户UID
            'data'      => [
                'imgs'       => $img,             //需要检测的文本
                'tokenId'   => $dataId,           //用户账号标识， 建议使用贵司用户UID
            ]
        ];
        // 发送请求
        $res = Utill::httpRequest(static::$config['imgCheck']['checkUrl'], 'POST', json_encode($data), static::$headers, false);
        $res = json_decode($res,true);

        $result = [];
        if($res['code'] == 1100){
            foreach ($res['imgs'] as $val){
                if($val['code'] !== 1100){
                    $info = ['code' => 91001,'message' => '数据检测请求异常'];
                    $result = $info;
                    $val = [];
                    (new CheckContentLogService())->AddCheckContenLog(2,$sceneId,2,empty($val['requestId']) ? '' : $val['requestId'],$userId,$dataId,json_encode($data,JSON_UNESCAPED_UNICODE),json_encode($val,JSON_UNESCAPED_UNICODE));
                    continue;
                }
                (new CheckContentLogService())->AddCheckContenLog(2,$sceneId,2,empty($val['requestId']) ? '' : $val['requestId'],$userId,$dataId,json_encode($data,JSON_UNESCAPED_UNICODE),json_encode($val,JSON_UNESCAPED_UNICODE));

                if ($val['riskLevel'] == 'REJECT' || $val['riskLevel'] == 'REVIEW') { // PASS=>正常 REVIEW=>可疑  REJECT=>违规
//                    $info[$val['btId']] = ['code' => 91002,'message' => '违规数据'];
                    $info = ['code' => 91002,'message' => '存在不合规内容 请调整'];
                    $result = $info;
//                    return $info;
                }
                if ($val['riskLevel'] == 'PASS') { // 建议动作，2：建议删除，1：建议审核，0：建议通过
//                    $info[$val['btId']] = ['code' => 200,'message' => '数据一切正常'];
                    $info = ['code' => 200,'message' => '数据一切正常'];
                }
            }
        }else{
            //请求异常
            return ['code' => 200,'message' => '数据检测请求异常'];
        }
        $info = !empty($result) ? $result : $info;
        return $info;
    }

    /**
     * 视频检测
     * @param $dataId
     * @param $userId
     * @param $content
     * @param $sceneId
     * @return array
     */
    public static function videoCheck($dataId,$userId,$content,$sceneId)
    {
        // imgType类型分布
        //POLITICS：涉政识别 VIOLENCE：暴恐识别 BAN：违禁识别 PORN：色情识别 AD：广告识别 OCR：图片中的文字风险识别
        // imgBusinessType可选值：/SCREEN ：特殊画⾯识别/SCENCE ：场景画⾯识别/ QR ：⼆维码识别/ FACE ：⼈脸识别/ QUALITY ：图像质量识别/ MINOR ：未成年⼈识别/ LOGO ：商企LOGO识别/ BEAUTY ：颜值识别/ OBJECT ：物品识别/ STAR ：公众⼈物识别
        //audioType枚举值 POLITICS：涉政识别 PORN：色情识别 AD：广告识别 MOAN：娇喘识别 ABUSE：辱骂识别 ANTHEN：国歌识别 AUDIOPOLITICAL：声音涉政 NONE :不检测音频
        // 拼装请求内容
        $strategy = self::$config['videoCheck']['eventId'][$sceneId];
        $data = [
            'accessKey'         => static::$accessKey,                               //应用秘钥
            'appId'             => static::$appId,                                   //应用ID
            'eventId'           => $sceneId,                                         //事件标识
            'imgType'           => $strategy['imgType'],                             //检测监管类型
            'audioType'         => $strategy['audioType'],                           //音频需要识别的监管类型
            'imgBusinessType'   => $strategy['imgBusinessType'],                     //识别的业务类型
            'callback'          => static::$url . '/getVideoSMCheck',                //人工审核结果回调通知到客户的URL,
            'btId'              => $dataId,                                  // 人工审核结果回调通知到客户的URL,
            'data'              => [
                'url'                   => $content['url'],  //需要检测的视频URL
                'btId'                  => $dataId,   //视频唯一标识
                'tokenId'               => $userId,   //用户唯一标识
                'detectFrequency'       => 5,                 //截帧频率间隔
                'videoTitle'            => $content['video_title'],  //视频名称
                'extra' => [
                    'passThrough' => $content,
                ],
            ]
        ];
        // 发送请求
        $res = Utill::httpRequest(static::$config['videoCheck']['checkUrl'], 'POST', json_encode($data), static::$headers, false);
        $res = json_decode($res,true);

        if($res['code'] == 1100){ //成功
            return ['code' => 200,'message' => '数据一切正常'];
        }else{
            return $res;
        }
    }


    /**
     * 直播流检测
     * @param $dataId
     * @param $userId
     * @param $content
     * @param $sceneId
     * @return array|mixed
     */
    public static function liveCheck($dataId,$userId,$content,$sceneId)
    {
        //监管类型imgType枚举值//POLITICS：涉政识别 //VIOLENCE：暴恐识别 //BAN：违禁识别 //PORN：色情识别 //AD：广告识别//OCR：图片中的文字风险识别
        //imgBusinessType 枚举值可选值： SCREEN：特殊画面识别 SCENCE：场景画面识别 QR：二维码识别 FACE：人脸识别 QUALITY：图像质量识别 MINOR：未成年人识别 LOGO：商企LOGO识别 BEAUTY：颜值识别 OBJECT：物品识别 STAR：公众人物识别
        //audioType枚举值 POLITICS：涉政识别 PORN：色情识别 AD：广告识别 MOAN：娇喘识别 ABUSE：辱骂识别 ANTHEN：国歌识别 AUDIOPOLITICAL：声音涉政 NONE :不检测音频
        // 拼装请求内容
        $strategy = self::$config['liveCheck']['eventId'][$sceneId];

        $data = [
            'accessKey'         => static::$accessKey,                      //应用秘钥
            'appId'             => static::$appId,                          //应用ID
            'eventId'           => $sceneId,                                //事件标识
            'imgType'           => $strategy['imgType'],                    //业务监管类型
            'imgBusinessType'   => $strategy['imgBusinessType'],            //商业监管类型
            'audioType'         => $strategy['audioType'],                  //音频需要识别的监管类型
            'callback'          => static::$url . '/getLiveSMCheck',        //审核结果回调通知到客户的URL,
            'imgCallback'       => static::$url . '/getLiveSMCheck',        //图片回调地址,
            'data'              => [
                'tokenId'   => $dataId, //用户ID，
                'lang'      => 'zh',          //zh ：中文  en ：英语  ar ：阿语
                'streamType'=> 'NORMAL',      //目前支持 rtmp 、 rtmps 、 hls 、 http 、 https 协议
                'url'       => $content['url'],//要检测的流地址url参数（当streamType为NORMAL时必传）
                'room'      => 111, //个房间号
                'extra'     => [
                    'passThrough' => $content,//透传字段
                ],
                // 'agoraParam'=> [
                //     'appId'     => 'sadfdf',         //声网提供的应用标识
                //     'channel'   => 'sadfdf',         //声网提供的频道名
                //     'uid'       => $info['uid'],     //用户UID
                // ],
            ]
        ];

        // 发送请求
        $res = Utill::httpRequest(static::$config['liveCheck']['checkUrl'], 'POST', json_encode($data), static::$headers, false);
        $res = json_decode($res,true);

        if($res['code'] == 1100){
            //上传直播流成功
            return ['code' => 200,'message' => '数据一切正常'];
        }else{
            return $res;
        }
    }

    //停止直播检测
    public static function feedback($dataId,$userId,$content,$sceneId){}

    //打标签
    public static function videoSync($dataId,$userId,$content,$sceneId){}
    //语音检测
    public static function audioCheck($dataId,$userId,$content,$sceneId){}
    //付费视频检测
    public static function liveWallSolution($dataId,$userId,$content,$sceneId){}
    //语音直播检测
    public static function liveaudioCheck($dataId,$userId,$content,$sceneId){}
    //停止语音直播检测
    public static function liveaudioFeedback($dataId,$userId,$content,$sceneId){}
    //反作弊
    public static function antiCheating($dataId,$userId,$content,$sceneId){}
    //行为式验证码
    public static function verificationCode($dataId,$userId,$content,$sceneId){}
}
